define([
    
], function() {
    'use strict';

    let _allLayers = {};

    var getResolutions = function (firstDpi) {
        var resolution = firstDpi ? firstDpi : 360 / 256;
        var resolutions = [];
        var matrixIds = [];
        for (var z = 0; z <= 30; ++z) {
            resolutions[z] = resolution / Math.pow(2, z);
            matrixIds[z] = z;
        }
        return {
            resolutions: resolutions,
            matrixIds: matrixIds,
        };
    };
    // 设置默认分辨率模型
    var rs = getResolutions(0.703125);


    // 默认天地图底图
    _allLayers["tiandituLayerdt"] = new ol.layer.Tile({
        opacity: 1,
        source: new ol.source.XYZ({
            projection: 'EPSG:4326',
            tileUrlFunction: function (tileCoord) {
                var url = 'http://t{0-7}.tianditu.gov.cn/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=643be9d1157982875dedbf77dcebf67c';
                var z = tileCoord[0] + 1;
                var x = tileCoord[1];
                var y = -tileCoord[2] - 1;
                var serverId = Math.round(Math.random() * 7);
                url = url.replace(/\{[0-9]-[0-9]\}/, serverId);
                return url.replace('{z}', z.toString()).replace('{y}', y.toString()).replace('{x}', x.toString());
            },
            tileGrid: new ol.tilegrid.TileGrid({
                        extent: [-180,-90,180,90],
                        origin: [-180,90],
                        resolutions: rs['resolutions'],
                        tileSize: 256,
                    }),
        }),
        zIndex: 8
    });
    
    // 默认天地图标注图层
    _allLayers["tiandituLayerbz"] = new ol.layer.Tile({
        opacity: 1,
        source: new ol.source.XYZ({
            projection: 'EPSG:4326',
            tileUrlFunction: function (tileCoord) {
                var url = 'http://t{0-7}.tianditu.gov.cn/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=643be9d1157982875dedbf77dcebf67c';
                var z = tileCoord[0] + 1;
                var x = tileCoord[1];
                var y = -tileCoord[2] - 1;
                var serverId = Math.round(Math.random() * 7);
                url = url.replace(/\{[0-9]-[0-9]\}/, serverId);
                return url.replace('{z}', z.toString()).replace('{y}', y.toString()).replace('{x}', x.toString());
            },
            tileGrid: new ol.tilegrid.TileGrid({
                        extent: [-180,-90,180,90],
                        origin: [-180,90],
                        resolutions: rs['resolutions'],
                        tileSize: 256,
                    }),
        }),
        zIndex: 100
    });

    // Mapzone政区区划
    var url = 'http://www.stgz.org.cn/MapzoneDataJH/c7faa30c-a5f3-4771-9da3-eb4b2708ccf8/{z}/{x}/{y}/tile.png';
    _allLayers["tileMapZoneMapLayer"] = new ol.layer.Tile({
        opacity: 1,
        source: new ol.source.XYZ({
            projection: 'EPSG:4326',
            url: url
        }),
        zIndex: 9
    });

    // 影像地图
    var url = 'http://t2.tianditu.gov.cn/DataServer?T=img_c&X={x}&Y={y}&L={z}&tk=d5b24677cd5d66023be61f408eeaf45a';
    _allLayers["tileTDTMapLayer"] = new ol.layer.Tile({
        opacity: 1,
        source: new ol.source.XYZ({
            projection: 'EPSG:4326',
            url: url
        })
    });

    
    /**
     * Create an overlay to anchor the popup to the map.
     */
    // var overlay = new ol.Overlay(/** @type {olx.OverlayOptions} */ ({
    //     element: document.getElementById('popup'),
    //     autoPan: false,
    //     autoPanAnimation: {
    //       duration: 250
    //     }
    // }));
    var projection = new ol.proj.Projection({
            code: "EPSG:4326",
            units: ol.proj.Units.DEGREES,
            extent: [-180,-90,180,90]
    });
    var scaleLineControl = new ol.control.ScaleLine();
    var map = new ol.Map({
        target: 'map',
        view: new ol.View({
            center: [105.66746201038362, 35.862170650959015],
            projection: projection,
            zoom: 4,
            maxZoom: 18,
            minZoom: 5
        }),
        controls: ol.control.defaults({
            attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
              collapsible: false
            }),
            attribution: false
          }).extend([
            scaleLineControl
        ]),
        layers: [
            _allLayers["tiandituLayerdt"],
            _allLayers["tiandituLayerbz"],
            _allLayers["tileMapZoneMapLayer"]
        ],
        interactions: ol.interaction.defaults({
            doubleClickZoom: false,// 取消双击放大功能交互
            mouseWheelZoom: true, // 取消滚动鼠标中间的滑轮交互
            shiftDragZoom: false, // 取消shift+wheel左键拖动交互
       })
    });

    
    var bzTileLoadFunction = function (imageTile, src) {
        // 使用滤镜 将白色修改为深色
        let img = new Image()
        // img.crossOrigin = ''
        // 设置图片不从缓存取，从缓存取可能会出现跨域，导致加载失败
        img.setAttribute('crossOrigin', 'anonymous')
        img.onload = function () {
            let canvas = document.createElement('canvas')
            let w = img.width
            let h = img.height
            canvas.width = w
            canvas.height = h
            let context = canvas.getContext('2d')
            context.filter = 'grayscale(98%) invert(1000%) sepia(0%) hue-rotate(180deg) saturate(1600%) brightness(80%) contrast(90%)'
            context.drawImage(img, 0, 0, w, h, 0, 0, w, h)
            imageTile.getImage().src = canvas.toDataURL('image/png')
        }
        img.src = src
    }
    
    var dtTileLoadFunction = function (imageTile, src) {
        // 使用滤镜 将白色修改为深色
        let img = new Image()
        // img.crossOrigin = ''
        // 设置图片不从缓存取，从缓存取可能会出现跨域，导致加载失败
        img.setAttribute('crossOrigin', 'anonymous')
        img.onload = function () {
            let canvas = document.createElement('canvas')
            let w = img.width
            let h = img.height
            canvas.width = w
            canvas.height = h
            let context = canvas.getContext('2d')
            context.filter = 'grayscale(98%) invert(100%) sepia(20%) hue-rotate(180deg) saturate(1600%) brightness(80%) contrast(90%)'
            context.drawImage(img, 0, 0, w, h, 0, 0, w, h)
            imageTile.getImage().src = canvas.toDataURL('image/png')
        }
        img.src = src
    }
    var dellTileLoadFunction = function (imageTile, src) {
        // 使用滤镜 将白色修改为深色
        let img = new Image()
        // img.crossOrigin = ''
        // 设置图片不从缓存取，从缓存取可能会出现跨域，导致加载失败
        img.setAttribute('crossOrigin', 'anonymous')
        img.onload = function () {
            let canvas = document.createElement('canvas')
            let w = img.width
            let h = img.height
            canvas.width = w
            canvas.height = h
            let context = canvas.getContext('2d')
            context.filter = ''
            context.drawImage(img, 0, 0, w, h, 0, 0, w, h)
            imageTile.getImage().src = canvas.toDataURL('image/png')
        }
        img.src = src
    }
    
    document.getElementById("transStyle").onclick = function (e) {
        if (!this.classList.value.includes("dark")) {
            setdarktheam(this);
        }else{
            setlighttheam(this);
        }
    }

    function setdarktheam(dom_context) {
        _allLayers["tiandituLayerdt"].getSource().setTileLoadFunction(dtTileLoadFunction);
        _allLayers["tiandituLayerbz"].getSource().setTileLoadFunction(bzTileLoadFunction);
        _allLayers["tileMapZoneMapLayer"].getSource().setTileLoadFunction(bzTileLoadFunction);
        dom_context.classList.add("dark");
        $("#map_tool .button").css({"backgroundColor": '#fff',"color": '#10131a'});
    }
    function setlighttheam(dom_context) {
        _allLayers["tiandituLayerbz"].getSource().setTileLoadFunction(dellTileLoadFunction);
        _allLayers["tiandituLayerdt"].getSource().setTileLoadFunction(dellTileLoadFunction);
        _allLayers["tileMapZoneMapLayer"].getSource().setTileLoadFunction(dellTileLoadFunction);
        dom_context.classList.remove("dark");
        $("#map_tool .button").css({"backgroundColor": '#10131a',"color" : '#fff'});
    }
    
    // 设置zoom
    let _zoom = map.getView().getZoom();
    document.getElementById("map_level").innerText = Math.round(_zoom);
    map.on('moveend', function () {
        _zoom = map.getView().getZoom();
        document.getElementById("map_level").innerText = Math.round(_zoom);
    })
    // 打印点击位置坐标
    // map.on('click', function (e) {
    //     console.log(map.getCoordinateFromPixel(e.pixel));
    // })

    function addLayer(layerId, layer) {
        _allLayers[layerId] = layer;
        layer.set('c_layerId', layerId);
        map.addLayer(layer);
    }
    function getMap() {
        return map;
    }
    function getLayerById(layerId) {
        return _allLayers[layerId];
    }
    function removeLayer(layerId, bool) {
        let layer = _allLayers[layerId];
        if (layer) {
            layer.setVisible(false)
            map.removeLayer(layer);
            delete _allLayers[layerId];
        }
    }
    function showLayer(layerId) {
        let layer = _allLayers[layerId];
        layer.setVisible(true);
    }
    function hideLayer(layerId) {
        let layer = _allLayers[layerId];
        layer.setVisible(false);
    }

    return {
        addLayer: addLayer,
        getMap: getMap,
        getLayerById: getLayerById,
        removeLayer: removeLayer,
        setdarktheam: setdarktheam,
        setlighttheam: setlighttheam,
        showLayer: showLayer,
        hideLayer: hideLayer,
    }
});